package com.guohengspace.mq.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 * @date 2023/3/27 11:13
 */

@Slf4j
public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    private static ObjectMapper mapper1 = new ObjectMapper();

    static {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
//        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);

        mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper1.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }


    public static ObjectMapper getObjectMapper() {
        return mapper;
    }

    /**
     * 获取JSON指定节点value
     *
     * @param src
     * @param path
     * @return
     */
    public static String findValByPath(String src, String path) {
        try {
            JsonNode root = mapper.readTree(src);
            JsonNode node = root.findValue(path);
            if (node == null) {
                return null;
            }
            return node.asText();
        } catch (Exception e) {
            log.warn("获取指定节点json异常:src:{},path:{}", src, path, e);
        }
        return null;

    }


    /**
     * 获取JSON指定节点value
     *
     * @param src
     * @param path
     * @return
     */
    public static List<String> findValsByPaths(String src, String path) {
        try {
            JsonNode root = mapper.readTree(src);
            List<JsonNode> nodes = root.findValues(path);
            return nodes.stream().map(p -> p.toString()).collect(Collectors.toList());
        } catch (Exception e) {
//            log.warn("获取指定节点json异常{}",e.getMessage(),e);
        }
        return null;

    }

    public static <T> Map toMap(T t) {
        try {
            String s = mapper.writeValueAsString(t);
            Map map = mapper.readValue(s, Map.class);
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;

    }


    public static <T> T toBean(String json, Class<T> eventClass) throws IOException {
        return mapper1.readValue(json, eventClass);
    }
}
